package com.gtmonitor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;

import android.app.TabActivity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;

import com.gtmonitor.graphics.GraphicsActivity;
import com.gtmonitor.storage.StorageActivity;

public class GTmonitorActivity extends TabActivity {
    
    private final static String TAG = "GTmonitor";
    private TabHost mTab = null;
    public static boolean externalStorageWriteable = false;
    public static int screenWidth = 0;
    
    void verifyExternalStorage() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            // We can read and write the media
            externalStorageWriteable = true;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            // We can only read the media
            externalStorageWriteable = false;
        } else {
            // Something else is wrong. It may be one of many other states, but all we need
            // to know is we can neither read nor write
            externalStorageWriteable = false;  
        }
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        CompatPanel panel = CompatPanel.getInstance(this);
        screenWidth = panel.getScreenWidth();
        Log.d(TAG, "Screen width " + screenWidth);

        JNIInterface.getInstance();
        // Fix orientation
        setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 
     
        // Hide status bar
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // Different Android version
        verifyExternalStorage();
        
        setContentView(R.layout.maintab);
        this.setTitle(R.string.AppTitle);

        if(GTmonitorService.getInstance() == null) {
            startService(new Intent(this, GTmonitorService.class));
        }
        
        mTab = getTabHost();
        //mTab.getTabWidget().setDividerDrawable(R.drawable.tab_divider);

        // TODO: Charts and Misc should be internationalized
        setupTab(new TextView(this), "Charts", new Intent(this, GraphicsActivity.class));
        setupTab(new TextView(this), "Misc",  new Intent(this, StorageActivity.class));
        
        Log.i(TAG, "GTmonitorActivity init");
    }
    
    private void setupTab(View view, String tag, Intent intent) {
        View tabView = createTabView(mTab.getContext(), tag);
        TabSpec setContent = mTab.newTabSpec(tag)
                             .setIndicator(tabView)
                             .setContent(intent);
        mTab.addTab(setContent);
    }
    
    private static View createTabView(Context context, String text) {
        View view = LayoutInflater.from(context).inflate(R.layout.tabcontent, null);
        TextView tv = (TextView)view.findViewById(R.id.tabsText);
        tv.setText(text);
        return view;
    }
    
    void nativeCrashed() {
        new RuntimeException("crashed here (native trace should follow after the Java trace)").printStackTrace();
        startActivity(new Intent(this, CrashHandler.class));
    }
    
    static boolean tryEmailAuthor(Context c, boolean isCrash, String body)
    {
        String addr = c.getString(R.string.author_email);
        Intent i = new Intent(Intent.ACTION_SEND);
        String modVer = "";
        try {
            Process p = Runtime.getRuntime().exec(new String[]{"getprop","com.gtmonitor"});
            modVer = readAllOf(p.getInputStream()).trim();
        } catch (Exception e) {}
        if (modVer.length() == 0) modVer = "original";
        // second empty address because of http://code.google.com/p/k9mail/issues/detail?id=589
        i.putExtra(Intent.EXTRA_EMAIL, new String[]{addr, ""});
        i.putExtra(Intent.EXTRA_SUBJECT, MessageFormat.format(c.getString(
                    isCrash ? R.string.crash_subject : R.string.email_subject),
                    getVersion(c), Build.MODEL, modVer, Build.FINGERPRINT));
        i.setType("message/rfc822");
        i.putExtra(Intent.EXTRA_TEXT, body!=null ? body : "");
        try {
            c.startActivity(i);
            return true;
        } catch (ActivityNotFoundException e) {
            try {
                // Get the OS to present a nicely formatted, translated error
                c.startActivity(Intent.createChooser(i,null));
            } catch (Exception e2) {
                e2.printStackTrace();
                Toast.makeText(c, e2.toString(), Toast.LENGTH_LONG).show();
            }
            return false;
        }
    }
    
    static String readAllOf(InputStream s) throws IOException
    {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(s),8096);
        String line;
        StringBuilder log = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            log.append(line);
            log.append("\n");
        }
        return log.toString();
    }
    
    static String getVersion(Context c)
    {
        try {
            return c.getPackageManager().getPackageInfo(c.getPackageName(),0).versionName;
        } catch(Exception e) { return c.getString(R.string.unknown_version); }
    }
}
